import React, { useEffect, useState } from 'react';
import { RouterProvider } from 'react-router-dom';
import { ConfigProvider, App as AntdApp, Spin } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { FeedbackSystem, ErrorBoundary, LoadingProvider } from './components/ui';
import { useAuthStore } from './services/store';
import { setMessageInstance } from './utils/message';

import router from './router';
import 'dayjs/locale/zh-cn';
import dayjs from 'dayjs';

// 设置dayjs为中文
dayjs.locale('zh-cn');

// Ant Design 主题配置
const theme = {
  token: {
    colorPrimary: '#1890ff',
    colorSuccess: '#52c41a',
    colorWarning: '#faad14',
    colorError: '#ff4d4f',
    colorInfo: '#1890ff',
    borderRadius: 6,
    wireframe: false
  },
  components: {
    Layout: {
      headerBg: '#fff',
      siderBg: '#001529'
    },
    Menu: {
      darkItemBg: '#001529',
      darkSubMenuItemBg: '#000c17'
    }
  }
};

function AppContent() {
  const { message } = AntdApp.useApp();
  
  // 设置全局message实例
  useEffect(() => {
    setMessageInstance(message);
  }, [message]);
  
  return (
    <RouterProvider router={router} />
  );
}

function App() {
  const { checkAuth } = useAuthStore();
  const [initialLoading, setInitialLoading] = useState(true);

  useEffect(() => {
    // 应用启动时检查认证状态
    const initializeApp = async () => {
      try {
        const token = localStorage.getItem('auth_token');
        if (token) {
          await checkAuth();
        }
        // 最小加载时间，确保用户看到加载动画
        await new Promise(resolve => setTimeout(resolve, 500));
      } catch (error) {
        console.error('应用初始化失败:', error);
      } finally {
        setInitialLoading(false);
      }
    };

    initializeApp();
  }, [checkAuth]);

  // 显示初始加载动画
  if (initialLoading) {
    return (
      <div className="fixed inset-0 bg-white flex items-center justify-center z-50">
        <div className="text-center">
          <div className="mb-6">
            <img 
              src="/logo.png"
              alt="加载中"
              className="h-16 w-16 mx-auto animate-pulse"
            />
          </div>
          <Spin size="large" />
          <div className="mt-4 text-gray-600 text-lg font-medium">
            正在加载应用...
          </div>
        </div>
      </div>
    );
  }

  // 错误报告处理
  const handleErrorReport = (error: any) => {
    console.error('应用错误报告:', error);
    // 这里可以添加错误上报逻辑，比如发送到监控服务
  };

  return (
    <ConfigProvider locale={zhCN} theme={theme}>
      <AntdApp>
        <LoadingProvider>
          <ErrorBoundary onError={handleErrorReport}>
            <FeedbackSystem onErrorReport={handleErrorReport}>
              <AppContent />
            </FeedbackSystem>
          </ErrorBoundary>
        </LoadingProvider>
      </AntdApp>
    </ConfigProvider>
  );
}

export default App;
